package mspbots.cw.business.core.activities;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.cw.business.core.BaseReceiver;
import mspbots.cw.common.ResultMsg;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * @author Jay.Yang
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class ActivitiesReceiver extends BaseReceiver {

    private final ActivitiesRepository activitiesRepository;

    //@RabbitListener(queues = "connect-wise.activities.tl")
    public void process(ResultMsg resultMsg) {
        JsonNode entityNode = resultMsg.getEntity();

        Activity data = super.objectMapper.convertValue(entityNode, Activity.class);
//        Activity data = new Activity();
        data.setId(null);
        data.setCwId(resultMsg.getId());
        data.setTenantCode(resultMsg.getTenantId());
        data.setSyncTime(resultMsg.getSyncDate());

        data.setStatusId(super.getLongValueId(entityNode.get("status")));
        data.setStatusName(super.getStringValueName(entityNode.get("status")));

        data.setCompanyId(super.getLongValueId(entityNode.get("company")));
        data.setCompanyName(super.getStringValueName(entityNode.get("company")));
        data.setCompanyIdentifier(super.getStringValueIdentifier(entityNode.get("company")));

        data.setContactId(super.getLongValueId(entityNode.get("contact")));
        data.setContactName(super.getStringValueName(entityNode.get("contact")));

        data.setUpdatedBy(super.getStringValue(entityNode.findValue("updatedBy")));
        data.setLastUpdatedTime(super.getDateTimeValue(entityNode.findValue("lastUpdated")));

        data.setTypeId(super.getLongValueId(entityNode.get("type")));
        data.setTypeName(super.getStringValueName(entityNode.get("type")));

        data.setAssignToId(super.getLongValueId(entityNode.get("assignTo")));
        data.setAssignToName(super.getStringValueName(entityNode.get("assignTo")));
        this.activitiesRepository.findByCwIdAndTenantCode(resultMsg.getId(), resultMsg.getTenantId())
                .map(result -> {
                    data.setId(result.getId());
                    return data;
                })
                .defaultIfEmpty(data)
                .flatMap(this.activitiesRepository::save).block(Duration.ofSeconds(10));
    }

}
